package com.ruoyi.web.controller.substation;

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SArea;
import com.ruoyi.system.domain.SSubstationDevice;
import com.ruoyi.system.service.ISAreaService;
import com.ruoyi.system.service.ISSubstationDeviceService;
import io.swagger.annotations.ApiOperation;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SSubstation;
import com.ruoyi.system.service.ISSubstationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 变电站信息Controller
 * 
 * @author ruoyi
 * @date 2023-07-05
 */
@Api(tags = "变电站信息管理")
@RestController
@RequestMapping("/substation/substation")
public class SSubstationController extends BaseController
{
    @Autowired
    private ISSubstationService sSubstationService;

    @Autowired
    private ISSubstationDeviceService substationDeviceService;

    /**
     * 查询变电站信息列表
     */
    @ApiOperation("获取变电站信息列表")
    @PreAuthorize("@ss.hasPermi('substation:substation:list')")
    @GetMapping("/list")
    public TableDataInfo list(SSubstation sSubstation)
    {
        startPage();
        List<SSubstation> list = sSubstationService.getList(sSubstation);
        return getDataTable(list);
    }

    /**
     * 获取变电站名称列表
     */
    @ApiOperation("获取变电站名称列表")
    @PreAuthorize("@ss.hasPermi('substation:substation:list')")
    @GetMapping("/substationNameList")
    public AjaxResult substationNameList(SSubstation sSubstation)
    {
        List<SSubstation> list = sSubstationService.getList(sSubstation);

//        Comparator com = Collator.getInstance(Locale.CHINA);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (int i = 1; i <= 26; i++) {
            String word = String.valueOf((char)(96 + i)).toUpperCase();
            Map<String, Object> map = new TreeMap<>();
            List<SSubstation> temp = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                SSubstation substation = list.get(j);
                String str = getFullSpell(substation.getSubstationName()).substring(0, 1);
                if(word.equals(str)){
                    temp.add(substation);
                }
            }
            map.put("key", word);
            map.put("value", temp);
            mapList.add(map);
        }

        List<SSubstation> temp = new ArrayList<>();
        Map<String, Object> map = new TreeMap<>();
        for (int j = 0; j < list.size(); j++) {
            SSubstation substation = list.get(j);
            String str = getFullSpell(substation.getSubstationName()).substring(0, 1);
            if("#".equals(str)){
                temp.add(substation);
            }
        }
        map.put("key", "#");
        map.put("value", temp);
        mapList.add(map);

        return success(mapList);
    }

    /**
     * 导出变电站信息列表
     */
    @ApiOperation("导出变电站信息列表")
    @PreAuthorize("@ss.hasPermi('substation:substation:export')")
    @Log(title = "变电站信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SSubstation sSubstation)
    {
        List<SSubstation> list = sSubstationService.list(sSubstation.queryWrapper());
        ExcelUtil<SSubstation> util = new ExcelUtil<SSubstation>(SSubstation.class);
        util.exportExcel(response, list, "变电站信息数据");
    }

    /**
     * 导入变电站信息
     */
    @ApiOperation("导入变电站信息")
    @PreAuthorize("@ss.hasPermi('substation:substation:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        String message = "操作成功";
        try {
            message = sSubstationService.importData(file);
        }catch (IllegalStateException e){
            throw new ServiceException("请检查表格格式是否为文本格式!");
        }
        return success(message);
    }

    /**
     * 获取变电站信息详细信息
     */
    @ApiOperation("获取变电站信息详细")
    @ApiImplicitParam(name = "id", value = "变电站信息ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('substation:substation:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(sSubstationService.getById(id));
    }

    /**
     * 新增变电站信息
     */
    @ApiOperation("新增变电站信息")
    @PreAuthorize("@ss.hasPermi('substation:substation:add')")
    @Log(title = "变电站信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SSubstation sSubstation)
    {
        return toAjax(sSubstationService.save(sSubstation));
    }

    /**
     * 修改变电站信息
     */
    @ApiOperation("更新变电站信息")
    @PreAuthorize("@ss.hasPermi('substation:substation:edit')")
    @Log(title = "变电站信息", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping
    public AjaxResult edit(@RequestBody SSubstation sSubstation)
    {
        return toAjax(sSubstationService.updateSubstationById(sSubstation));
    }

    /**
     * 删除变电站信息
     */
    @ApiOperation("删除变电站信息")
    @ApiImplicitParam(name = "ids", value = "变电站信息ID集合", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('substation:substation:remove')")
    @Log(title = "变电站信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids)
    {
        for (String id : ids) {
            long count = substationDeviceService.count(new LambdaQueryWrapper<SSubstationDevice>()
                    .eq(SSubstationDevice::getSubstationId, id));
            if(count > 0){
                throw new ServiceException("变电站已绑定设备！");
            }
        }
        return toAjax(sSubstationService.removeByIds(ids));
    }

    public static void main(String[] args) {
        String fullSpell = getFullSpell("%");
        System.out.println(fullSpell);
    }
    /**
     * 获取汉字串拼音，英文字符不变
     * @param chinese 汉字串
     * @return 汉语拼音
     */
    public static String getFullSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append("#");
            }
        }
        return pybf.toString();
    }
}
